package com.hainatong.shiphelper.module.QSHE.fragment;

import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.LinearLayout;
import androidx.core.content.ContextCompat;
import com.blankj.utilcode.util.StringUtils;
import com.hainatong.shiphelper.MvvmLazyFragment;
import com.hainatong.shiphelper.R;
import com.hainatong.shiphelper.databinding.FragmentDoucmentFileBinding;
import com.hainatong.shiphelper.module.QSHE.viewmodel.QSHEViewModel;
import com.just.agentweb.AgentWeb;


public class DocumentFileFragment extends MvvmLazyFragment<FragmentDoucmentFileBinding, QSHEViewModel>
{
    private static String DOCUMENT_TAG = "DocumentFileFragment";

    private String docUrl = "";

    private AgentWeb agentWebView;

    public static DocumentFileFragment newInstance(String scanCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( DOCUMENT_TAG , scanCode );
        DocumentFileFragment docFragment = new DocumentFileFragment();
        docFragment.setArguments( bundle );
        return docFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_doucment_file;
    }

    @Override
    public int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        if(  args != null )
        {
            docUrl = args.getString(DOCUMENT_TAG , "");
        }
    }

    @Override
    protected void onRetryBtnClick()
    {
    }

    @Override
    protected void initView(View view)
    {
        /*
        viewDataBinding.recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        viewDataBinding.recyclerview.setHasFixedSize(true);
        viewDataBinding.recyclerview.setAdapter(adapter);
        */
        /*
        List<FunctionEntity> funList = new ArrayList<>();
        funList.add(new FunctionEntity("PRO-01-01文件发放控制表.doc",""+ Constants.DOCUMENT_TAG,0));
        funList.add(new FunctionEntity("PRO-01-01文件发放控制表.pdf",""+Constants.DOCUMENT_TAG,0));
        */
    }

    @Override
    protected void lazyLoad()
    {
        /*
        adapter.setList( funList );
        adapter.setOnItemClickListener((adapter1, view1, position) -> {
            ToastUtils.showShort( adapter.getItem(position).getTitle() );
            if( adapter.getItem(position).getTitle().endsWith(".doc") )
            {
                Flowable.create(emitter->
                        {
                            LogUtils.e( "开始处理my2.doc  thread= " + Thread.currentThread().getName() + " ID = "+Thread.currentThread().getId() );
                            emitter.onNext("my2.doc");
                            emitter.onComplete();
                        }
                        , BackpressureStrategy.BUFFER )
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(fileName->
                                {
                                    if( !getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).exists() )
                                    {
                                        getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).mkdir();
                                    }
                                    LogUtils.e( "复制my2.doc  thread= " + Thread.currentThread().getName() + " ID = "+Thread.currentThread().getId() );
                                    AssetsCopyUtil.copyAssetsFile(getActivity(),getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath(),(String) fileName );
                                },throwable -> {

                                },()->
                                {
                                    LogUtils.e( "打开my2.doc  thread= " + Thread.currentThread().getName() + " ID = "+Thread.currentThread().getId() );
                                    File docFile = new File(getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath()+"/my2.doc" );
                                    startActivity( OpenFileUtil.getWordFileIntent( getActivity() , docFile) );
                                }
                        );
            }
            else if( adapter.getItem(position).getTitle().endsWith(".pdf") )
            {
                Flowable.create(emitter -> {
                    emitter.onNext("test1.pdf");
                    emitter.onComplete();
                },BackpressureStrategy.BUFFER)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe( fileName -> {
                                    if( !getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).exists() )
                                    {
                                        getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).mkdir();
                                    }
                                    AssetsCopyUtil.copyAssetsFile(getActivity(),getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath(), (String) fileName);
                                }
                                , throwable -> {

                                } ,()->{

                                    File docFile = new File(getActivity().getApplication().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath()+"/test1.pdf" );
                                    startActivity( OpenFileUtil.getPdfFileIntent( getActivity() , docFile) );
                                } );
            }
        });
        */
         /*
            Bundle bundle = new Bundle();
            bundle.putString(Constants.FRAGMNET_TYPE , Constants.VIEW_DOCUMENT_VIEW);
            bundle.putString(Constants.SCAN_CONTENT_CODE , adapter.getItem(position).getTitle() );
            ComFragmentActivity.start(getActivity(),bundle);
            */

        if( !StringUtils.isEmpty( docUrl ) )
        {
            String mUrl = "http://docs.google.com/gview?embedded=true&url=" +docUrl;

            agentWebView = AgentWeb.with( this )
                    .setAgentWebParent(viewDataBinding.webContent,new LinearLayout.LayoutParams(-1,-1))
                    .useDefaultIndicator(ContextCompat.getColor( getActivity(),R.color.green ))
                    //.setWebChromeClient( new MyWebChromeClient() )
                    //.setWebViewClient( new MyWebViewClient() )
                    .setSecurityType(AgentWeb.SecurityType.DEFAULT_CHECK)
                    .createAgentWeb()
                    .ready()
                    .go(mUrl);


            //清缓存和记录
            agentWebView.getWebCreator().getWebView().clearCache(true);
            agentWebView.getWebCreator().getWebView().clearHistory();
            agentWebView.getWebCreator().getWebView().requestFocus();

            WebSettings webSettings = agentWebView.getWebCreator().getWebView().getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setSupportZoom(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setAllowFileAccess(true);

            webSettings.setUseWideViewPort(true);
            webSettings.setBuiltInZoomControls(true);

            webSettings.setLoadWithOverviewMode(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        }

    }





    @Override
    public void onPause()
    {
        super.onPause();
        if( agentWebView !=null )
        {
            agentWebView.getWebLifeCycle().onPause();
        }
    }

    @Override
    public void onResume()
    {
        super.onResume();
        if( agentWebView !=null )
        {
            agentWebView.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onDestroy()
    {
        if( agentWebView !=null )
        {
            agentWebView.getWebLifeCycle().onDestroy();
        }
        super.onDestroy();
    }
}
